package com.app.scale.scale;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;

import com.app.scale.basis.BasisActivity;
import com.app.scale.basis.Constants;
import com.app.scale.bean.BasisBean;
import com.app.scale.bean.GoodsListBean;
import com.app.scale.bean.GoodsListData;
import com.app.scale.bean.LoginBean;
import com.app.scale.bean.SupplierListBean;
import com.app.scale.bean.SupplierListData;
import com.app.scale.bean.UserInfoBean;
import com.app.scale.bean.UserInfoList;
import com.app.scale.util.SoftKeyboardUtil;
import com.app.scale.util.UnitUtil;
import com.caysn.autoreplyprint.AutoReplyPrint;
import com.google.gson.Gson;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.LongByReference;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.vandin.weigher.sdk.connector.IWeigh;
import com.vandin.weigher.sdk.connector.IWeighCallback;
import com.vandin.weigher.sdk.connector.WeightData;
import com.vandin.weigher.sdk.weigher.WeightSerialPort;

import java.math.BigDecimal;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import my.DialogUtils;
import my.LogUtil;
import my.MathUtils;
import my.MySharedPreferences;
import my.SystemParamsUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

public class ScalePresenterImpl implements ScalePresenter,IWeighCallback{
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    String oldWeight="0";
    String scaleWeight="0";  //真实的秤重量

    private IWeigh iWeigh;
    ScaleView scaleView;
    MySharedPreferences mSp;

    //静默拍照参数
    private boolean isSend = false;
    private Pointer h = Pointer.NULL;

    public ScalePresenterImpl(ScaleView scaleView){
        this.scaleView = scaleView;
    }

    @Override
    public void getGoodsListByFsg(ScaleActivity activity, String fsg) {
        MyParams params = new MyParams();
        activity.showProgress();
        params.put("aid", LoginBean.getInstance().getAcode());
        params.put("fsg", fsg);
        MyHttpUtils.get(Constants.URL_GOODF_SELECT_ALL, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (activity.isFinishing()) return;
                        GoodsListBean goodsListBean = (GoodsListBean) result;
                        scaleView.getGoodsListResultByFsg(goodsListBean,fsg);
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if (activity.isFinishing()) return;
                        super.onFailure(httpWhat, result);
//                        DialogUtils.showErrorDialog(activity,((BasisBean) result).getStatusInfo());
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        activity.dismissProgress();
                    }
                },
                0, GoodsListBean.class);

    }


    @Override
    public void showGoodsOption(Context mContext,GoodsListBean goodsListBean) {
        String[] items = goodsListBean.getAllNameList().toArray(new String[goodsListBean.getAllNameList().size()]);
        new QMUIDialog.CheckableDialogBuilder(mContext)
                .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        GoodsListData goodsData = goodsListBean.getList().get(which);
                        scaleView.getGoodsOptionsResult(goodsData);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void getSupplierInfoByCode(ScaleActivity activity,String code) {
        MyParams params = new MyParams();
        activity.showProgress();
        params.put("cardno", code);
        MyHttpUtils.get(Constants.URL_COMPAY_SELECT_BY_CARD_NO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (activity.isFinishing()) return;
                        SupplierListBean supplierListBean = (SupplierListBean) result;
                        if(supplierListBean.getSupplier() != null){
                            scaleView.getSupplierResult(supplierListBean.getSupplier());
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if(activity.isFinishing())return;
                        if(result != null &&   !TextUtils.isEmpty(((BasisBean) result).getStatusInfo())){
                            DialogUtils.showErrorDialog(activity,((BasisBean) result).getStatusInfo());
                        }else {
                            DialogUtils.showErrorDialog(activity,"异常！");
                        }
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        activity.dismissProgress();
                    }
                },
                0, SupplierListBean.class);
    }

    @Override
    public void getSupplierInfoByBno(ScaleActivity activity,String bno) {
        MyParams params = new MyParams();
        activity.showProgress();
        params.put("bno", bno);
        MyHttpUtils.get(Constants.URL_COMPAY_SELECT_BY_CARD_NO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (activity.isFinishing()) return;
                        SupplierListBean supplierListBean = (SupplierListBean) result;
                        if(supplierListBean.getSupplier() != null){
                            scaleView.getSupplierResult(supplierListBean.getSupplier());
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if(activity.isFinishing())return;
                        if(result != null &&   !TextUtils.isEmpty(((BasisBean) result).getStatusInfo())){
                            DialogUtils.showErrorDialog(activity,((BasisBean) result).getStatusInfo());
                        }else {
                            DialogUtils.showErrorDialog(activity,"异常！");
                        }
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        activity.dismissProgress();
                    }
                },
                0, SupplierListBean.class);
    }

    @Override
    public void isJiJiaYuan(ScaleActivity mContext, List<UserInfoBean> jijiayuanList) {

        QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(mContext);
        builder.setTitle("请计价员刷卡")
                .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                .setPlaceholder("输入或者扫描卡片")
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        new Handler().postDelayed(new  Runnable(){
                            public  void  run() {
                                SoftKeyboardUtil.hideKeyboard(mContext);
                            }
                        },  100 );
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String text = builder.getEditText().getText().toString();
                        if (!TextUtils.isEmpty(text)) {
                            boolean isJijiayuan = false;
                            for (UserInfoBean userInfoBean : jijiayuanList){
                                if(userInfoBean.getCdno().equals(text)){
                                    isJijiayuan = true;
                                    scaleView.isJiJiaYuan(true,userInfoBean);
                                }
                            }
                            if(!isJijiayuan){
                                getUserInfoByCardNo(mContext,text,jijiayuanList);
                            }
                            dialog.dismiss();
                            new Handler().postDelayed(new  Runnable(){
                                public  void  run() {
                                    SoftKeyboardUtil.hideKeyboard(mContext);
                                }
                            },  100 );
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void isJiJiaYuan(ScaleActivity activity, List<UserInfoBean> jijiayuanList, String no) {
        if (!TextUtils.isEmpty(no)) {
            boolean isJijiayuan = false;
            for (UserInfoBean userInfoBean : jijiayuanList){
                if(userInfoBean.getCdno().equals(no)){
                    isJijiayuan = true;
                    scaleView.isJiJiaYuan(true,userInfoBean);
                }
            }
            if(!isJijiayuan){
                getUserInfoByCardNo(activity,no,jijiayuanList);
            }
        }
    }

    public void getUserInfoByCardNo(ScaleActivity mContext,String cardNo,List<UserInfoBean> jijiayuanList){
        MyParams params = new MyParams();
        params.put("cardno", cardNo);
        mContext.showProgress();
        MyHttpUtils.get(Constants.URL_SELECT_BY_CAR_NO, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                if(mContext.isFinishing())return;
                UserInfoList userInfoList = (UserInfoList) result;
                if(userInfoList.isJijiayuan()){
                    jijiayuanList.addAll(userInfoList.getList());
                    scaleView.isJiJiaYuan(true,userInfoList.getList().get(0));
                }else {
                    scaleView.isJiJiaYuan(false,null);
                }
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
                if(mContext.isFinishing())return;
//                super.onFailure(httpWhat, result);
                scaleView.isJiJiaYuan(false,null);
            }

            @Override
            public void onFinish(int httpWhat) {
                if(mContext.isFinishing())return;
                mContext.dismissProgress();
            }
        }, 0, UserInfoList.class);
    }


    //----------------以下秤的接口------------------

    @Override
    public void onConnect(int status, String str, boolean b) {
        /**
         * status =1 ; str =正在连接……  ; b = true
         * status =2 ; str =连接成功    ; b = true
         * status =7 ; str =暂停读取    ; b = false
         * status =4 ; str =断开成功    ; b = true
         * status =10 ; str =读取重量    ; b = false           IControl.GetWeight();调用就会回调这个
         */
//        LogUtil.d("ScaleActivity==onConnect==status =="+ status);
//        LogUtil.d("ScaleActivity==onConnect==str =="+ str);
//        LogUtil.d("ScaleActivity==onConnect==b =="+ b);

        switch (status){
            case 2:
                iWeigh.GetWeight();
                break;
        }
    }

    @Override
    public void onReceiveData(String frame, String weight, boolean isSta) {
        //weight的格式 ====      +   0.515
        LogUtil.d("ScaleActivity==weight =="+ weight);
        if(weight.contains("-")){
            scaleView.dashboardViewSetValue(0);
            scaleWeight = String.valueOf(0);
            return;
        }
        if(oldWeight.equals(weight)){
            return;
        }else {
            oldWeight = weight;
        }

        try {
//            a = a.substring(0,(a.indexOf(".")+2));
            BigDecimal bd   =  new BigDecimal(MathUtils.multiply(UnitUtil.getNumByString(weight),"2"));
            bd   =   bd.setScale(1,BigDecimal.ROUND_HALF_UP);

//            LogUtil.d("ScaleActivity==weightzzzzz =="+ bd.toString());
            float scale = Float.parseFloat(bd.toString());
            scaleView.dashboardViewSetValue(scale);
            scaleWeight = String.valueOf(scale);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }


    @Override
    public IWeigh getIWeigh(Context mContext) {
        if(mSp == null){
            mSp = new MySharedPreferences(mContext);
        }
        if (iWeigh != null) {
            iWeigh.disconnect();
        }
        WeightData weightData = new WeightData();
        weightData.setPort(mSp.getPort());
        weightData.setBaudrate(mSp.getBaudrate());
        iWeigh = new WeightSerialPort(mContext, this, weightData);
        iWeigh.OpenScaleUart();
        return iWeigh;
    }

    @Override
    public String getScaleWeight() {
        return scaleWeight;
    }

    @Override
    public String getOldScaleWeight() {
        return oldWeight;
    }

    @Override
    public void closeIWeigh() {
        if (iWeigh != null) {
            iWeigh.StopRead();
            iWeigh.disconnect();
            iWeigh = null;
        }
    }

    @Override
    public void changeSupplierLData(BasisActivity activity, SupplierListData data) {
        MyParams params = new MyParams();
        activity.showProgress();
        Gson gson = new Gson();
        String a = gson.toJson(data);
        params.putJson(a);

        MyHttpUtils.postJson(Constants.URL_COMPAY_UPDATE_BY_ID, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                if(activity.isFinishing())return;
                BasisBean basisBean = (BasisBean) result;
                scaleView.printMessage("溯源码添加完毕");
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
                if(activity.isFinishing())return;
//                super.onFailure(httpWhat, result);
                if(result != null &&   !TextUtils.isEmpty(((BasisBean) result).getStatusInfo())){
                    DialogUtils.showErrorDialog(activity,((BasisBean) result).getStatusInfo());
                }else {
                    DialogUtils.showErrorDialog(activity,"异常！");
                }
            }

            @Override
            public void onFinish(int httpWhat) {
                if(activity.isFinishing())return;
                activity.dismissProgress();
            }
        }, 0, BasisBean.class);
    }

    @Override
    public void settlement(ScaleActivity activity, GoodsListBean goodsListBean, SupplierListData supplierData,UserInfoBean jijiayuan) {
        if(supplierData == null){
            DialogUtils.showWarningDialog(activity,"供应商请刷卡");
            return;
        }


        if(jijiayuan == null || TextUtils.isEmpty(jijiayuan.getUno())){
            jijiayuan = new UserInfoBean();
            jijiayuan.setUno(LoginBean.getInstance().getUno());
            jijiayuan.setUname(LoginBean.getInstance().getUname());
        }

        submit(activity,goodsListBean,supplierData,jijiayuan);



//        switch (supplierData.getCfs()){
//            case "代理商":
//                if(TextUtils.isEmpty(supplierData.getEditTra1())
//                        &&TextUtils.isEmpty(supplierData.getEditTra2())
//                        &&TextUtils.isEmpty(supplierData.getEditTra3())){
//                    DialogUtils.showErrorDialog(activity,"请填写代理商溯源重量");
//                    return;
//                }
//
//                StringBuffer str = new StringBuffer();
//                if(MathUtils.compareTo(supplierData.editTra1AddTra1(),goodsListBean.getAllTra1Weight())== -1){
//                    str.append("银针溯源重量不足\n");
//                }
//                if(MathUtils.compareTo(supplierData.editTra2AddTra2(),goodsListBean.getAllTra2Weight())== -1){
//                    str.append("牡丹溯源重量不足\n");
//                }
//                if(MathUtils.compareTo(supplierData.editTra2AddTra2(),goodsListBean.getAllTra3Weight())== -1){
//                    str.append("寿眉溯源重量不足\n");
//                }
//
//                if(TextUtils.isEmpty(str.toString())){
//                    submit(activity,goodsListBean,supplierData,jijiayuan);
//                }else {
//                    DialogUtils.showWarningDialog(activity, ""+str.toString(), "继续", new SweetAlertDialog.OnSweetClickListener() {
//                        @Override
//                        public void onClick(SweetAlertDialog sweetAlertDialog) {
//                            sweetAlertDialog.dismiss();
//                            submit(activity,goodsListBean,supplierData,jijiayuan);
//                        }
//                    });
//                }
//
//                break;
//            case "茶农":
//                if(TextUtils.isEmpty(supplierData.getTra1())&&TextUtils.isEmpty(supplierData.getTra2())&&TextUtils.isEmpty(supplierData.getTra3())){
//                    DialogUtils.showErrorDialog(activity,"无溯源重量");
//                    return;
//                }
//
//                StringBuffer strCN = new StringBuffer();
//
//                if(MathUtils.compareTo(supplierData.getTra1(),goodsListBean.getAllTra1Weight())== -1){
//                    strCN.append("银针溯源重量不足\n");
//                }
//                if(MathUtils.compareTo(supplierData.getTra2(),goodsListBean.getAllTra2Weight())== -1){
//                    strCN.append("牡丹溯源重量不足\n");
//                }
//                if(MathUtils.compareTo(supplierData.getTra3(),goodsListBean.getAllTra3Weight())== -1){
//                    strCN.append("寿眉溯源重量不足\n");
//                }
//
//                if(!TextUtils.isEmpty(strCN.toString())){
//                    DialogUtils.showErrorDialog(activity,""+strCN.toString());
//                    return;
//                }
//                submit(activity,goodsListBean,supplierData,jijiayuan);
//                break;
//        }

    }



    private void submit(ScaleActivity activity,GoodsListBean goodsListBean, SupplierListData supplierData,UserInfoBean jijiayuan){

        MyParams params = new MyParams();
        activity.showProgress();
        Gson gson = new Gson();
        String a = gson.toJson(goodsListBean.getSubmitBean(activity,supplierData,jijiayuan.getUno()));
        params.putJson(a);

        MyHttpUtils.postJson(Constants.URL_LEAF_INSERT, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                if(activity.isFinishing())return;
                BasisBean basisBean = (BasisBean) result;
                GoodsListBean.GoodsSubmitBean submitBean = new Gson().fromJson(basisBean.getResultData(), GoodsListBean.GoodsSubmitBean.class);
                toPrint(activity,submitBean,goodsListBean,supplierData,jijiayuan);
                scaleView.settlementSuccess();
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
                if(activity.isFinishing())return;
//                super.onFailure(httpWhat, result);
                if(result != null &&   !TextUtils.isEmpty(((BasisBean) result).getStatusInfo())){
                    DialogUtils.showErrorDialog(activity,((BasisBean) result).getStatusInfo());
                }else {
                    DialogUtils.showErrorDialog(activity,"异常！");
                }
            }

            @Override
            public void onFinish(int httpWhat) {
                if(activity.isFinishing())return;
                activity.dismissProgress();
            }
        }, 0, BasisBean.class);
    }




    //----------------以下都是打印的接口------------------
    public void toPrint( ScaleActivity activity,GoodsListBean.GoodsSubmitBean submitBean,GoodsListBean goodsListBean, SupplierListData supplierData,UserInfoBean jijiayuan ){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Test_Pos_SampleTicket_58MM_1(activity,submitBean,goodsListBean,supplierData,jijiayuan);
                scaleView.printFinish();
            }
        }).start();
    }


    private void Test_Pos_SampleTicket_58MM_1(ScaleActivity activity,GoodsListBean.GoodsSubmitBean submitBean,
                                              GoodsListBean goodsListBean, SupplierListData supplierData,UserInfoBean jijiayuan ) {
        Pointer h = OpenPort();
        if (h != Pointer.NULL) {

            AutoReplyPrint.INSTANCE.CP_Pos_ResetPrinter(h);
            AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteMode(h);
            AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteEncoding(h, AutoReplyPrint.CP_MultiByteEncoding_UTF8);


            AutoReplyPrint.INSTANCE.CP_Pos_SetAlignment(h, AutoReplyPrint.CP_Pos_Alignment_HCenter);
            AutoReplyPrint.INSTANCE.CP_Pos_SetTextScale(h, 1, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, ""+LoginBean.getInstance().getBname()+"收购凭证\r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "————————————————\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");


            AutoReplyPrint.INSTANCE.CP_Pos_SetAlignment(h, AutoReplyPrint.CP_Pos_Alignment_Left);
            AutoReplyPrint.INSTANCE.CP_Pos_SetTextScale(h, 0, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "秤编号:  "+ SystemParamsUtils.getAndroidID(activity)+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "凭证号:  "+submitBean.getTid()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "日期:  "+ TimeUtils.getCurrentTimeByFormat(TimeUtils.TIME_FOMART_DAY)+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "供应商:  "+ supplierData.getCna()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "身份证:  "+ supplierData.getCht()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "--------------------------------\n");


            for (int i= 0;i<goodsListBean.getList().size();i++){
                GoodsListData goodsData =goodsListBean.getList().get(i);
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "品名:  "+ goodsData.getGna()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "累计净重:  "+ goodsData.getGwt()+"斤"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "去皮:  "+ goodsData.getPwt()+"斤"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "单价:  "+ goodsData.getGpr()+"元"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "金额:  "+ MathUtils.multiply(goodsData.getGwt(),goodsData.getGpr())+"元"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "累计:  "+ goodsData.getAcc()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "--------------------------------\n");
            }

            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "金额合计:  "+ goodsListBean.getAllTotal()+"元"+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "重量合计:  "+ goodsListBean.getAllWeight()+"斤"+"\n");
//            if(TextUtils.isEmpty(submitBean.getTra1Tra2Tra3())){
//                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "溯源余量:  "+ "0"+"\n");
//            }else {
//                if(!TextUtils.isEmpty(submitBean.getTra1())){
//                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "银针溯源余量:  "+ submitBean.getTra1()+"\n");
//                }
//                if(!TextUtils.isEmpty(submitBean.getTra2())){
//                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "牡丹溯源余量:  "+ submitBean.getTra2()+"\n");
//                }
//                if(!TextUtils.isEmpty(submitBean.getTra3())){
//                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "寿眉溯源余量:  "+ submitBean.getTra3()+"\n");
//                }
//            }
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "称重员:"+ LoginBean.getInstance().getUname()+"   计价员 :"+ jijiayuan.getUname()+"\n");

            AutoReplyPrint.INSTANCE.CP_Pos_Beep(h, 1, 500);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

            if(!TextUtils.isEmpty(supplierData.getAutoBno())){
                Bitmap bitmap = CodeUtils.createImage(supplierData.getAutoBno(), 150, 150, null);
                AutoReplyPrint.CP_Pos_PrintRasterImageFromData_Helper.PrintRasterImageFromBitmap(h, bitmap.getWidth(), bitmap.getHeight(), bitmap, AutoReplyPrint.CP_ImageBinarizationMethod_Thresholding, AutoReplyPrint.CP_ImageCompressionMethod_None);
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            }


            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

            QueryPrintResult(h);
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
        }
    }





    private Pointer OpenPort() {
        Pointer h = Pointer.NULL;
        h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x4B43,PID:0x3538", 1);

        if (h == Pointer.NULL) {
            scaleView.printMessage("OpenPort Failed");
        }
        return h;
    }

    @Override
    public void ClosePort() {
        if (h != Pointer.NULL) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
            h = Pointer.NULL;
        }
    }

    private boolean QueryPrintResult(Pointer h) {
        boolean result = AutoReplyPrint.INSTANCE.CP_Pos_QueryPrintResult(h, 30000);
//        scaleView.printMessage(result ? "Print Success" : "Print Failed");
        scaleView.printMessage(result ? "打印成功" : "打印失败");
        if (!result) {
            LongByReference printer_error_status = new LongByReference();
            LongByReference printer__info_status = new LongByReference();
            LongByReference timestamp_ms_printer_status = new LongByReference();
            if (AutoReplyPrint.INSTANCE.CP_Printer_GetPrinterStatusInfo(h, printer_error_status, printer__info_status, timestamp_ms_printer_status)) {
                AutoReplyPrint.CP_PrinterStatus status = new AutoReplyPrint.CP_PrinterStatus(printer_error_status.getValue(), printer__info_status.getValue());
                String error_status_string = String.format("Printer Error Status: 0x%04X", printer_error_status.getValue() & 0xffff);
                if (status.ERROR_OCCURED()) {
                    if (status.ERROR_CUTTER())
                        error_status_string += "[ERROR_CUTTER]";
                    if (status.ERROR_FLASH())
                        error_status_string += "[ERROR_FLASH]";
                    if (status.ERROR_NOPAPER())
                        error_status_string += "[ERROR_NOPAPER]";
                    if (status.ERROR_VOLTAGE())
                        error_status_string += "[ERROR_VOLTAGE]";
                    if (status.ERROR_MARKER())
                        error_status_string += "[ERROR_MARKER]";
                    if (status.ERROR_ENGINE())
                        error_status_string += "[ERROR_ENGINE]";
                    if (status.ERROR_OVERHEAT())
                        error_status_string += "[ERROR_OVERHEAT]";
                    if (status.ERROR_COVERUP())
                        error_status_string += "[ERROR_COVERUP]";
                    if (status.ERROR_MOTOR())
                        error_status_string += "[ERROR_MOTOR]";
                }
                scaleView.printMessage(error_status_string);
            } else {
                scaleView.printMessage("CP_Printer_GetPrinterStatusInfo Failed");
            }
        }
        return result;
    }



}
